﻿
using Castle.Core.Internal;
using Coldairarrow.Business.Interface;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.Interface;
using Coldairarrow.Util;
using Dynamitey;
using Microsoft.VisualBasic;
using Newtonsoft.Json.Linq;
using OfficeOpenXml.Drawing.Slicer.Style;
using org.apache.zookeeper.data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Tracing;
using System.Drawing;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using static AutoMapper.Internal.CollectionMapperExpressionFactory;
using static Coldairarrow.Business.Interface.EC_ReqDTO_SyncOrder.Biz_Content;
using static Coldairarrow.Entity.Interface.YDOrdersDTO.Orders.Delivery;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace Coldairarrow.Business.Interface
{
    public class OL_Rep_EcommerceSalesInterfaceBusiness : Interface_BaseBusiness, IJob_Business, ITransientDependency
    {
        public List<OL_FilterDTO> Filters { get; set; }

        public Base_InterfaceOption queryOption { get; set; }
        public Base_InterfaceOption insertOption { get; set; }
        public Base_InterfaceOption upDateOption { get; set; }
        public Base_InterfaceOption deleteOption { get; set; }
        public OL_Rep_EcommerceSalesInterfaceBusiness()
        {
            this.InterfaceName = "电商销售数据";
            //获取字段的映射关系
            tableField = GetMapField("editRow");
            //索引字段
            Keys = GetKeys("editRow");
            indexFields.Add(Keys.Where(X => X.Type == "K").First().Field);
            //查询过滤条件
            Filters = new List<OL_FilterDTO>();
            //数据库连接
            ConString = JsonSettingHelper.GetSetting("Database:BaseDb:ConnectionString");
            SqlDb = (SqlServerHelper)DbHelperFactory.GetDbHelper(EFCore.Sharding.DatabaseType.SqlServer, ConString);

            //获取此接口的所有API信息
            this.interfaceOption = SqlDb.GetListBySql<Base_InterfaceOption>(@$"SELECT * FROM  Base_InterfaceOption(NOLOCK) WHERE Name='{InterfaceName}' ");
            this.queryOption = this.interfaceOption.Where(o => o.OperateType == "getFilterRows").First();//查询API配置
            this.insertOption = this.interfaceOption.Where(o => o.OperateType == "addRow").First();//新增API配置
            this.upDateOption = this.interfaceOption.Where(o => o.OperateType == "editRow").First();//更行API配置
            this.deleteOption = this.interfaceOption.Where(o => o.OperateType == "deleteRow").First();//删除API配置

            //查询执行前的事件
            BeforeQueryEvent += InterfaceBusiness_BeforeQueryEvent;
            //查询执行中的事件
            OnQueryEvent += InterfaceBusiness_OnQueryEvent;
            //执行非查询请求中的事件
            OnNoQueryEvent += InterfaceBusiness_OnNoQueryEvent;

        }

        /// <summary>
        /// 执行非查询请求中时间
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="noQueryEventArgs"></param>
        private void InterfaceBusiness_OnNoQueryEvent(object sender, NoQueryEventArgs noQueryEventArgs)
        {
            //API请求是否成功
            noQueryEventArgs.Success = noQueryEventArgs.Result["success"].ToString().ToBool();
        }

        /// <summary>
        /// 查询执行前的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_BeforeQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //执行查询前添加过滤条件
            if (queryEventArgs.Page.Filters.IsNullOrEmpty() && !Filters.IsNullOrEmpty())
            {
                queryEventArgs.Page.Filters = Filters;
            }

        }

        /// <summary>
        /// 查询执行中的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="queryEventArgs"></param>
        private void InterfaceBusiness_OnQueryEvent(object sender, QueryEventArgs queryEventArgs)
        {
            //是否查询完成
            if (queryEventArgs.Result["data"]["rows"].ToList().Count == 0)
            {
                queryEventArgs.Page.Complete = true;
            }
            //向总行中添加新的行
            queryEventArgs.Rows.AddRange(queryEventArgs.Result["data"]["rows"].ToList());
            //获取总页数
            queryEventArgs.Page.Total = queryEventArgs.Result["data"]["total"].ToString().ToInt();
            //获取查询成功标志
            queryEventArgs.Success = queryEventArgs.Result["success"].ToString().ToBool();
        }


        /// <summary>
        /// 执行增删改查业务
        /// </summary>
        public async void ExecuteInterface()
        {

            try
            {
                
                //获取开始日期
                string dateForm = DateTime.Now.AddDays(-queryOption.ExcInterval).ToString("yyyy-MM-dd");



                //获取One_Link亚马逊MSKU信息
                AMZ_MSKUInterfaceBusiness msku = new AMZ_MSKUInterfaceBusiness();
                msku.Filters.Clear();
                msku.Filters.Add(
               //13:>,14>=15:<,16<=
               new OL_FilterDTO() { ControlId = "", DataType = 2, SpliceType = 1, FilterType = 14, Value = "" }//只查询亚马逊的MSKU
           );
                List<AMZ_MSKU> AMZ_MSKUList = await msku.QueryAsync<AMZ_MSKU>(msku.queryOption, msku.tableField, msku.SqlDb);
                AMZ_MSKUList.ForEach(x =>
                {
                    //SKU
                    List<AssTable> table = x.sku_lock.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.sku_lock_T = table[0];
                    x.sku_lock = x.sku_lock_T.IsNullOrEmpty() ? "" : x.sku_lock_T.sid;
                    //店铺
                    table = x.shop.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.shop_T = table[0];
                    x.shop = x.shop_T.IsNullOrEmpty() ? "" : x.shop_T.sid;
                });

                //获取One_Link SKU信息
                OL_LocalSKUInterfaceBusiness localSKU = new OL_LocalSKUInterfaceBusiness();
                localSKU.Filters.Clear();
                localSKU.Filters.Add(
               //13:>,14>=15:<,16<=
               new OL_FilterDTO() { ControlId = "", DataType = 15, SpliceType = 1, FilterType = 14, Value = "" }//FDATE字段过滤日开始700天前到现在的数据
           );
                List<LocalSKU> localSKUList = await localSKU.QueryAsync<LocalSKU>(localSKU.queryOption, localSKU.tableField, localSKU.SqlDb);


                //获取店铺
                OL_ShopInterfaceBusiness OL_Shop = new OL_ShopInterfaceBusiness();
                OL_Shop.Filters.Add(
            new OL_FilterDTO() { ControlId = "", DataType = 29, SpliceType = 1, FilterType = 8, Value = "" }
                //new OL_FilterDTO() { ControlId = "661d1c34387bc49b7a55d06e", DataType = 15, SpliceType = 1, FilterType = 14, Value = "2024-11-24" }
                );
                List<OL_Shop> shopList = OL_Shop.Query<OL_Shop>(OL_Shop.queryOption, OL_Shop.tableField, OL_Shop.SqlDb);
                shopList.ForEach(x =>
                {
                    //平台
                    List<AssTable> table = x.Platform_.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) x.Platform_ = table.IsNullOrEmpty() ? "" : table.First().sid;
                });
                List<OL_Rep_EcommerceSales> saleskLsit = new List<OL_Rep_EcommerceSales>();

                //获取亚马逊销售数据
                List<OL_Rep_EcommerceSales> sales = GetAMZSales(dateForm, AMZ_MSKUList, shopList);
                saleskLsit.AddRange(sales);
                //获取易仓销售数据
                sales = GetECSales(dateForm, AMZ_MSKUList, shopList, localSKUList);
                saleskLsit.AddRange(sales);


                List<OL_Rep_EcommerceSales> sourceData = new List<OL_Rep_EcommerceSales>();
                sourceData = saleskLsit;






                //获取目标数据
                Filters.Clear();
                Filters.Add(
                //13:>,14>=15:<,16<=
                new OL_FilterDTO() { ControlId = "685b6a20a31d84c7f66f92b5", DataType = 15, SpliceType = 1, FilterType = 14, Value = dateForm }//FDATE字段过滤日开
            );
                List<OL_Rep_EcommerceSales> targetData = await QueryAsync<OL_Rep_EcommerceSales>(queryOption, tableField, SqlDb);
                foreach (var item1 in targetData)
                {
                    //MSKU
                    List<AssTable> table = item1.MSKU.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) item1.MSKU = table[0].sid;
                    else item1.MSKU = "";
                    //平台
                    table = item1.Platform.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) item1.Platform = table[0].sid;
                    else item1.Platform = "";
                    //SKU
                    table = item1.SKU.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) item1.SKU = table[0].sid;
                    else item1.SKU = "";
                    //店铺
                    table = item1.Seller.ToObject<List<AssTable>>();
                    if (!table.IsNullOrEmpty() && table.Count > 0) item1.Seller = table[0].sid;
                    else item1.Seller = "";
                }
                if (this.State > 0 && sourceData.Count > 0)
                {
                    //更新
                    #region
                    List<OL_Rep_EcommerceSales> updataItem = sourceData.Intersect(targetData, new ComparerFromKeys<OL_Rep_EcommerceSales>(Keys, "RowId")).ToList();//获取交集(更新项)
                    List<OL_RowDTO> updataData = ConvertOL_Row(updataItem, tableField);//需要更新的数据集合
                    ExecuteNoQuery<OL_RowDTO>(updataData, upDateOption, SqlDb);//执行更新
                    #endregion

                    //新增
                    #region
                    List<OL_Rep_EcommerceSales> insertItem = sourceData.Except(targetData, new ComparerFromKey<OL_Rep_EcommerceSales>(indexFields.First(), "RowId")).ToList();//获取源数据对目标数据的差集(新增项)
                    List<OL_RowDTO> insertData = ConvertOL_Row(insertItem, tableField);//需要新增的数据集合
                    ExecuteNoQuery<OL_RowDTO>(insertData, insertOption, SqlDb);//执行插入行
                    #endregion

                    //删除
                    #region
                    List<OL_Rep_EcommerceSales> deleteItem = targetData.Except(sourceData, new ComparerFromKey<OL_Rep_EcommerceSales>(indexFields.First(), "RowId")).ToList();//获取目标数对据源数据的差集(删除项)
                    List<OL_Rep_EcommerceSales> repeatItem = targetData.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    //将重复的项也一起加入删除的列表
                    deleteItem.AddRange(repeatItem);
                    //筛选出删除列表中重复的项
                    var temp = deleteItem.GroupBy(x => x.GetPropertyValue(indexFields.First())).Where(x => x.Count() > 1).Select(x => x.FirstOrDefault()).ToList();
                    deleteItem.AddRange(temp);
                    List<OL_RowDTO> deleteData = ConvertOL_Row(deleteItem, tableField);//需要删除的数据集合
                    ExecuteNoQuery<OL_RowDTO>(deleteData, deleteOption, SqlDb);//执行删除行
                    #endregion
                }
            }


            catch (Exception ex)
            {
                AddLog(SqlDb, ex.Message, InterfaceName, "erro", "");
            }
        }




        /// <summary>
        /// 将源数据根据字典映射关系转换成OL_RowDTO
        /// </summary>
        /// <typeparam name="T">源数据</typeparam>
        /// <param name="sourceData">源数据</param>
        /// <param name="map">Key为目标字段名称，Value为源字段名称</param>
        /// <returns></returns>
        public List<OL_RowDTO> ConvertOL_Row<T>(List<T> sourceData, Dictionary<string, string> map)
        {
            List<OL_RowDTO> list = new List<OL_RowDTO>();
            object rowId;
            foreach (var item in sourceData)
            {
                rowId = item.GetPropertyValue("RowId");
                //需要新增的数据
                OL_RowDTO row = new OL_RowDTO() { RowId = rowId.IsNullOrEmpty() ? null : rowId.ToString(), Controls = new List<Control>() };
                foreach (var c in map)
                {
                    //获取字段的键值做判断
                    var field = Keys.Where(x => x.TField == c.Key).ToList();
                    string isKey = "";
                    if (field.Count > 0) isKey = field.First().Type;
                    //判断对象的字段是否存在
                    if (item.ContainsProperty(c.Value) && isKey != "N")
                    {
                        //存在则添加数据
                        row.Controls.Add(new Control() { ControlId = c.Key, Value = item.GetPropertyValue(c.Value) });
                    }
                }
                list.Add(row);
            }
            return list;
        }

        public List<OL_Rep_EcommerceSales> GetAMZSales(string dateForm, List<AMZ_MSKU> mskuList, List<OL_Shop> shopList)
        {
            //获取亚马逊报表
            List<PrdPerformance> amzSalesList = SqlDb.GetListBySql<PrdPerformance>(@$"SELECT seller_sku,sid,seller_name,OL_SKU,OL_MSKU,Date,volume,return_goods_count FROM SD_LX_PrdPerformance WHERE  (volume >0 OR return_goods_count >0) AND Date>='{dateForm}'");

            List<OL_Rep_EcommerceSales> dataList = new List<OL_Rep_EcommerceSales>();

            foreach (var item1 in amzSalesList.Where(x => !x.volume.IsNullOrEmpty() && x.volume.ToInt() > 0))
            {

                OL_Rep_EcommerceSales data = new OL_Rep_EcommerceSales();

                var msku = mskuList.Where(x => x.seller_sku == item1.seller_sku && x.sid == item1.sid);

                if (!msku.IsNullOrEmpty() && msku.Count() > 0)
                {
                    data.MSKU = msku.First().RowId;
                    data.SKU = msku.First().sku_lock.IsNullOrEmpty() ? "" : msku.First().sku_lock;
                }
                else
                {
                    data.MSKU = "";
                    data.SKU = "";
                }
                data.MSKU_S = item1.seller_sku;
                data.Date = item1.date;
                data.SellerId = item1.sid;
                data.Sales = item1.volume;
                var shop = shopList.Where(x => x.ID == item1.sid);
                if (!shop.IsNullOrEmpty())
                {
                    data.Seller = shop.FirstOrDefault().RowId;
                    data.Platform = shop.FirstOrDefault().Platform_;
                }
                data.ID = data.MSKU_S + data.SellerId + data.Date.ToDateTime().ToString("yyyy-MM-dd");
                dataList.Add(data);

            }

            return dataList;
        }

        public List<OL_Rep_EcommerceSales> GetECSales(string dateForm, List<AMZ_MSKU> mskuList, List<OL_Shop> shopList, List<LocalSKU> skuList)
        {

            //获取多平台订单
            List<Ec_OrderLIst> ecSalesList = SqlDb.GetListBySql<Ec_OrderLIst>(@$"SELECT a.order_id,a.refrence_no,a.order_code, a.status,a.date_create_platform,a.platform,b.product_sku_org,b.product_title,b.platform_sku,b.product_sku_list,b.qty,a.platform_user_name,a.user_account,a.creater_user_name,a.is_merge FROM SD_EC_OrderList a  
LEFT JOIN SD_EC_order_details b ON a.order_id=b.order_id 
WHERE  a.platform != 'amazon' AND a.platform != 'b2c' AND a.status NOT LIKE '%废弃%' AND a.status NOT LIKE '%付款未完成%' AND a.date_create_platform >='{dateForm}'");

            List<OL_Rep_EcommerceSales> dataList = new List<OL_Rep_EcommerceSales>();

            //账户名称里面有对应店铺的销量
            //var orderGroup = ecSalesList.GroupBy(x => x.refrence_no + x.product_sku_org);
            var orderGroup = ecSalesList.GroupBy(x => x.order_id + x.product_sku_org + x.product_sku_list);
            foreach (var g in orderGroup)
            {
                var first = g.First();
                OL_Rep_EcommerceSales data = new OL_Rep_EcommerceSales();
                //易仓订单平台/店铺命名
                data.SellerId = first.platform_user_name;
                //数量
                //data.Sales = first.qty;
                //日期
                data.Date = first.date_create_platform;
                //根据店铺维护的账户信息匹配电商店铺
                var shops = new List<OL_Shop>();
                //区分订单的店铺
                if (first.platform == "shopify" || first.platform == "ebay" || first.platform == "wayfairnew" || first.platform == "walmart" || first.platform == "ozon" || first.platform_user_name == "HD-Supply")//如果账户名称包含这些
                {
                    shops = shopList.Where(x => !x.Account.IsNullOrEmpty()).Where(x =>
                    {
                        var temp = x.Account.Split(",");
                        if (temp.Contains(first.platform_user_name)) return true;
                        else return false;
                    }).ToList();

                }
                else //账户名称为Teapplix的多平台店铺
                {
                    shops = shopList.Where(x => !x.Account.IsNullOrEmpty()).Where(x =>
                    {
                        bool flag = false;
                        var temp = x.Account.Split(",");
                        foreach (var item2 in temp)
                        {
                            if (first.refrence_no.Contains(item2)) flag = true;
                        }
                        return flag;
                    }).ToList();

                }
                //给店铺和平台赋值
                if (!shops.IsNullOrEmpty() && shops.Count > 0)
                {
                    data.Seller = shops.FirstOrDefault().RowId;
                    data.Platform = shops.FirstOrDefault().Platform_;
                }

                if (first.platform == "shopify" && first.date_create_platform.ToDateTime().ToString("yyyy-MM-dd") == "2025-08-28" && first.refrence_no == "#FG7479")
                {
                    var WW = "";
                }

                //根据MSKU判断是否是组合的产品，是则需要拆分不是直接统计
                if (first.product_sku_org.Contains("+"))
                {
                    List<OL_Rep_EcommerceSales> datas1 = GetSplitSales(g.ToList(), data, mskuList, skuList);
                    dataList.AddRange(datas1);
                }
                else if (first.platform_user_name == "Teapplix" && first.product_sku_list.Contains(","))//多平台的组合SKU拆分
                {
                    List<OL_Rep_EcommerceSales> datas3 = GetSplitSales_A(g.ToList(), data, mskuList, skuList);
                    dataList.AddRange(datas3);
                }
                else
                {
                    List<OL_Rep_EcommerceSales> datas2 = GetSales(g.ToList(), data, mskuList, skuList);
                    dataList.AddRange(datas2);
                }
                
            }

            //将ID相同的行进行数量合并
            List<OL_Rep_EcommerceSales> res = new List<OL_Rep_EcommerceSales>();
            var group = dataList.GroupBy(x => x.ID);
            group.ForEach(x =>
        {
            if (x.Count() > 1)
            {
                OL_Rep_EcommerceSales first = x.First().DeepClone();
                first.Sales = x.Sum(y => y.Sales.ToInt()).ToString();
                first.SKU_EC = string.Join(",", x.Select(x => x.SKU_EC));
                first.CombMsku = string.Join(",", x.Select(x => x.CombMsku));
                res.Add(first);
            }
            else
            {
                res.Add(x.First());
            }

        });

            return res;
        }

        public List<OL_Rep_EcommerceSales> GetSplitSales(List<Ec_OrderLIst> orders, OL_Rep_EcommerceSales data, List<AMZ_MSKU> mskuList, List<LocalSKU> skuList)
        {
            List<OL_Rep_EcommerceSales> datas = new List<OL_Rep_EcommerceSales>();
            //List<Ec_OrderLIst> orders_c = orders.DeepClone();

            //将组合的MSKU拆分开
            var mskus = orders[0].product_sku_org.Replace("?", "").Replace(",", "").Split("+").ToList();

            //如果订单数量小于拆分产品数量，则需要查询是哪两个MSKU
            if (orders.Count() < mskus.Count())
            {
                List<string> ms = new List<string>();
                foreach (var item1 in orders)
                {
                    //比较原平台MSKU与易仓SKU的相似度,取相似度近的一个
                    string platform_sku = "";
                    double score = 0;
                    foreach (var item2 in mskus)
                    {
                        double temp = item2.LevenshteinDistance(item1.product_sku_list);
                        if (temp > score)
                        {
                            score = temp;
                            platform_sku = item2;
                        }
                    }
                    ms.Add(platform_sku);
                    mskus.Remove(platform_sku);
                }
                if (ms.Count > 0) mskus = ms;
            }
            foreach (var msku_ in mskus)
            {
                //根据平台SKU和店铺匹配msku
                var msku = mskuList.Where(x => x.seller_sku == msku_ && x.shop == data.Seller);
                //根据平台SKU和店铺匹配msku
                var sku = skuList.Where(x => x.SKU == orders[0].product_sku_list);
                OL_Rep_EcommerceSales data_ = data.DeepClone();
                
                 if (!sku.IsNullOrEmpty())
                {
                    var temp = sku.FirstOrDefault();
                    data_.SKU = temp.RowId;
                    data_.MSKU_S = orders[0].product_sku_list;
                }
                else if (!msku.IsNullOrEmpty())
                {
                    var temp = msku.FirstOrDefault();
                    data_.SKU = temp.sku_lock;
                    data_.MSKU = temp.RowId;
                    data_.MSKU_S = msku_;
                }
                data_.SKU_EC = orders[0].platform_sku;
                data_.SKU_EC_Warehouse = orders[0].product_sku_list;
                data_.CombMsku = orders[0].product_sku_org;
                data_.OrigName = orders[0].product_title;
                data_.Sales = orders[0].qty;
                data_.ID = data_.MSKU_S + data_.SellerId + data_.Date.ToDateTime().ToString("yyyy-MM-dd") + data_.OrigName.ToMD5String16();
                datas.Add(data_);
            }


            //需要将订单里面的所有项循环完才推出-前逻辑
            //while (orders.Count > 0 && false)
            //{
            //    //如果只有一个，判断是否组合MSKU直接就占用了一行,否则就是组合的MSKU两个中只发了一个
            //    if (orders.Count > 1 || orders[0].platform_sku.Contains("+"))
            //    {
            //        foreach (var msku_ in mskus)
            //        {
            //            //根据平台SKU和店铺匹配msku
            //            var msku = mskuList.Where(x => x.seller_sku == msku_ && x.shop == data.Seller);
            //            OL_Rep_EcommerceSales data_ = data.DeepClone();
            //            if (!msku.IsNullOrEmpty())
            //            {
            //                var temp = msku.FirstOrDefault();
            //                data_.SKU = temp.sku_lock;
            //                data_.MSKU = temp.RowId;
            //            }
            //            data_.SKU_EC = orders[0].platform_sku;
            //            data_.SKU_EC_Warehouse = orders[0].product_sku_list;
            //            data_.CombMsku = orders[0].product_sku_org;
            //            data_.OrigName = orders[0].product_title;
            //            data_.MSKU_S = msku_;
            //            data_.Sales = orders[0].qty;
            //            data_.ID = data_.MSKU_S + data_.SellerId + data_.Date.ToDateTime().ToString("yyyy-MM-dd") + data_.OrigName.ToMD5String16();
            //            datas.Add(data_);
            //        }
            //        //由于组合的MSKU已经拆分了两项，剩余的项不再循环，并且移除本次的循环项
            //        var item = orders.Where(x => x.platform_sku != orders[0].platform_sku && !x.platform_sku.Contains("+"));
            //        if (!item.IsNullOrEmpty()) orders.Remove(item.First());
            //        orders.Remove(orders[0]);
            //    }

            //    else
            //    {
            //        var data_ = data.DeepClone();
            //        //比较原平台MSKU与易仓SKU的相似度,取相似度近的一个
            //        string platform_sku = "";
            //        double score = 0;
            //        foreach (var item1 in mskus)
            //        {
            //            double temp = item1.LevenshteinDistance(orders[0].platform_sku);
            //            if (temp > score)
            //            {
            //                score = temp;
            //                platform_sku = item1;
            //            }
            //        }
            //        //根据MSKU和店铺匹配msku
            //        List<AMZ_MSKU> msku = new List<AMZ_MSKU>();
            //        if (!platform_sku.IsNullOrEmpty())
            //        {
            //            msku = mskuList.Where(x => x.seller_sku == platform_sku && x.shop == data_.Seller).ToList();
            //        }
            //        //如果原平台MSKU不存在则随机取第一条MSKU
            //        else
            //        {
            //            msku = mskuList.Where(x => x.seller_sku == mskus[0] && x.shop == data_.Seller).ToList();
            //        }

            //        if (!msku.IsNullOrEmpty() && msku.Count() > 0)
            //        {
            //            var msku_first = msku.FirstOrDefault();
            //            data_.SKU = msku_first.sku_lock;
            //            data_.MSKU = msku_first.RowId;
            //        }
            //        data_.SKU_EC = orders[0].platform_sku;
            //        data_.SKU_EC_Warehouse = orders[0].product_sku_list;
            //        data_.OrigName = orders[0].product_title;
            //        data_.MSKU_S = orders[0].product_sku_org;
            //        data_.Sales = orders[0].qty;
            //        data_.ID = data_.MSKU_S + data_.SellerId + data_.Date.ToDateTime().ToString("yyyy-MM-dd") + data_.OrigName.ToMD5String16();
            //        datas.Add(data_);
            //        //移除本次的循环项
            //        orders.Remove(orders[0]);
            //    }

            //}

            return datas;
        }



        public List<OL_Rep_EcommerceSales> GetSplitSales_A(List<Ec_OrderLIst> orders, OL_Rep_EcommerceSales data, List<AMZ_MSKU> mskuList, List<LocalSKU> skuList)
        {
            List<OL_Rep_EcommerceSales> datas = new List<OL_Rep_EcommerceSales>();
            //List<Ec_OrderLIst> orders_c = orders.DeepClone();

            //将组合的MSKU拆分开
            var mskus = orders[0].product_sku_list.Split(",").ToList();

            //如果订单数量小于拆分产品数量，则需要查询是哪两个MSKU
            //if (orders.Count() < mskus.Count())
            //{
            //    List<string> ms = new List<string>();
            //    foreach (var item1 in orders)
            //    {
            //        //比较原平台MSKU与易仓SKU的相似度,取相似度近的一个
            //        string platform_sku = "";
            //        double score = 0;
            //        foreach (var item2 in mskus)
            //        {
            //            double temp = item2.LevenshteinDistance(item1.product_sku_list);
            //            if (temp > score)
            //            {
            //                score = temp;
            //                platform_sku = item2;
            //            }
            //        }
            //        ms.Add(platform_sku);
            //        mskus.Remove(platform_sku);
            //    }
            //    if (ms.Count > 0) mskus = ms;
            //}
            foreach (var msku_ in mskus)
            {
                //根据平台SKU和店铺匹配msku
                var msku = mskuList.Where(x => x.seller_sku == msku_ && x.shop == data.Seller);
                //根据平台SKU和店铺匹配msku
                var sku = skuList.Where(x => x.SKU == msku_);
                OL_Rep_EcommerceSales data_ = data.DeepClone();
                if (!msku.IsNullOrEmpty())
                {
                    var temp = msku.FirstOrDefault();
                    data_.SKU = temp.sku_lock;
                    data_.MSKU = temp.RowId;
                }
                else if (!sku.IsNullOrEmpty())
                {
                    var temp = sku.FirstOrDefault();
                    data_.SKU = temp.RowId;
                }
                

                data_.SKU_EC = orders[0].platform_sku;
                data_.SKU_EC_Warehouse = msku_;
                data_.CombMsku = orders[0].product_sku_org;
                data_.OrigName = orders[0].product_title;
                data_.MSKU_S = msku_;
                data_.Sales = orders[0].qty;
                data_.ID = data_.MSKU_S + data_.SellerId + data_.Date.ToDateTime().ToString("yyyy-MM-dd") + data_.OrigName.ToMD5String16();
                datas.Add(data_);
            }

            return datas;
        }




        public List<OL_Rep_EcommerceSales> GetSales(List<Ec_OrderLIst> orders, OL_Rep_EcommerceSales data, List<AMZ_MSKU> mskuList, List<LocalSKU> skuList)
        {
            List<OL_Rep_EcommerceSales> datas = new List<OL_Rep_EcommerceSales>();
            foreach (var item1 in orders)
            {
                var data_ = data.DeepClone();
                //根据平台SKU和店铺匹配msku
                var msku = mskuList.Where(x => x.seller_sku == item1.product_sku_org && x.shop == data_.Seller);
                //根据平台SKU和店铺匹配msku
                var sku = skuList.Where(x => x.SKU == item1.product_sku_org);
                //根据平台SKU和店铺匹配msku
                var sku_warehouse = skuList.Where(x => x.SKU == item1.product_sku_list);
                if (!msku.IsNullOrEmpty())
                {
                    var msku_first = msku.FirstOrDefault();
                    data_.SKU = msku_first.sku_lock;
                    data_.MSKU = msku_first.RowId;
                }
                else if (!sku.IsNullOrEmpty())
                {
                    var temp = sku.FirstOrDefault();
                    data_.SKU = temp.RowId;
                }
                else if (!sku_warehouse.IsNullOrEmpty())
                {
                    var temp = sku_warehouse.FirstOrDefault();
                    data_.SKU = temp.RowId;
                }
                data_.SKU_EC = item1.platform_sku;
                data_.SKU_EC_Warehouse = orders[0].product_sku_list;
                data_.OrigName = item1.product_title;
                data_.MSKU_S = item1.product_sku_org;
                data_.Sales = item1.qty;
                data_.ID = data_.MSKU_S + data_.SellerId + data_.Date.ToDateTime().ToString("yyyy-MM-dd") + data_.OrigName.ToMD5String16();
                datas.Add(data_);

            }
            return datas;

        }

        /// <summary>
        /// 任务
        /// </summary>
        public void Job()
        {
            ExecuteInterface();
        }
    }

}
